package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author spt
 * @description 套餐SEVICE实现类
 * @date 2019/9/26
 **/
@Service
@Slf4j
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QiniuUtils qiniuUtils;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        log.info("[套餐-添加]data:{},checkgroupIds:{}",setmeal,checkgroupIds);
        // 调用DAO数据入库
        // 插入基本数据
        setMealDao.insert(setmeal);
        // 插入关联数据
        for (Integer checkgroupId : checkgroupIds) {
            setMealDao.insertSetMealAndCheckGroup(setmeal.getId(),checkgroupId);
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //DAO查询数据
        Page<Setmeal> page = setMealDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }


//    @Override
    @Scheduled(cron = "0 52 19 * * *")
    @Scheduled(cron = "0 0 2 * * *")
    public void clearGarbageImg() {

        SetOperations<String, String> stringStringSetOperations = redisTemplate.opsForSet();
        //计算两个集合的差集
        Set<String> difference = stringStringSetOperations.difference("imgSet", "imgSetMybatis");

        /*
        imgSet:1,2,3,4,5
        imgSetMybatis:1,2
        difference:3,4,5
         */
        for (String str : difference) {
            qiniuUtils.deleteFileFromQiniu(str);
        }
//        redisTemplate.boundSetOps("imgSet").remove();
//        redisTemplate.boundSetOps("imgSetMybatis").remove();
        log.info("[清理垃圾图片：{}]" + difference.size());
    }



    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }


    @Override
    public Setmeal selectById(Integer id) {

        return setMealDao.selectById(id);
    }


}
